package com.lxq.live.service;

import com.lxq.live.dao.UserRepository;
import com.lxq.live.pojo.RoleEnum;
import com.lxq.live.pojo.User;
import com.lxq.live.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    CommonUtil util;

    public List<User> findAll() {
        return userRepository.findAll();
    }

    public Map<String, String> addUser(User user) {
        var returnMap = new HashMap<String, String>();
        var validated = false;
        for (var i = 1; i <= 3; i++) {
            if (loadUserByUsername(user.getUserId()) == null) {
                user.setRole(RoleEnum.ordinary);
                userRepository.save(user);
                validated = true;
                break;
            } else {
                user.setUserId(util.generateUserId());
            }
        }
        if (!validated) {
            returnMap.put("result", "false");
            returnMap.put("because", "same password");
            return returnMap;
        }
        returnMap.put("result", "true");
        returnMap.put("userId", user.getUserId());
        return returnMap;
    }

    public User findByUserId(String userId) {
        return userRepository.findUserByUserId(userId);
    }

    @Override
    public User loadUserByUsername(String userId) throws UsernameNotFoundException {
        //System.out.println("loadUserByUsername has called user info="+user.toString());
        return userRepository.findUserByUserId(userId);
    }

    public void resetPassword(String userId,String newPassword){
        var user=findByUserId(userId);
        user.setPassword(util.passwordEncoder(newPassword));
        userRepository.save(user);
    }
}
